﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;

namespace CodeSaude.Infrastructure.CrossCutting.Util
{
    public static class EnumUtil
    {

        public static string GetEnumDescription(System.Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());

            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes != null && attributes.Length > 0)
                return attributes[0].Description;
            else
                return value.ToString();
        }

        public static Expected GetAttributeValue<T, Expected>(this System.Enum enumeration, Func<T, Expected> expression) where T : Attribute
        {
            T attribute =
              enumeration
                .GetType()
                .GetMember(enumeration.ToString())
                .FirstOrDefault(member => member.MemberType == MemberTypes.Field)
                .GetCustomAttributes(typeof(T), false)
                .Cast<T>()
                .SingleOrDefault();

            if (attribute == null)
                return default(Expected);

            return expression(attribute);
        }

        public static SelectList GetEnumSelectList<T>(int value)
        {
             var listSelectItens = (Enum.GetValues(typeof(T)).Cast<int>().Select(e => new SelectListItem() { Text = GetEnumDescription((Enum)Enum.Parse(typeof(T), e.ToString())), Value = e.ToString() })).ToList();

             return new SelectList(listSelectItens, "Value", "Text", value);
        }

    }
}
